package com.action.ioc.module;


import com.action.service.ChildRestServer;
import com.base.app_core.ioc.dao.HttpApiModule;
import com.base.app_core.model.Configure;
import com.base.app_core.model.ServerIP;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.liteorm.MyIChatDBHelpUtils;
import com.base.app_core.util.log.F;
import com.base.app_core.util.retrofit.MyRequestBodyConverter;

import java.util.List;
import java.util.Random;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Created by jiansheng.li on 2017/5/2.
 */
@Module
public class HttpSupperApiModule extends HttpApiModule {
    @Provides
    @Singleton
    public ChildRestServer provideSupperRestServer(OkHttpClient okHttpClient,MyIChatDBHelpUtils myIChatDBHelpUtils) {
        if(myIChatDBHelpUtils!=null){
            List<ServerIP> serverIPS=myIChatDBHelpUtils.getQueryAll(ServerIP.class);
            if(serverIPS!=null&&serverIPS.size()!=0){
                AppConstants.SERVER_URL=serverIPS.get(new Random().nextInt(serverIPS.size())).getUrl();
                F.j("switchse:"+AppConstants.SERVER_URL);
            }
        }
        Retrofit retrofit = new Retrofit.Builder().client(okHttpClient)
                .addConverterFactory(MyRequestBodyConverter.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(AppConstants.SERVER_URL)
                .build();
        return retrofit.create(ChildRestServer.class);
    }

    @Provides
    @Singleton
    Configure provideConfigure(MyIChatDBHelpUtils myIChatDBHelpUtils) {
        List<Configure> users = myIChatDBHelpUtils.getQueryAll(Configure.class);
        Configure configure = null;
        if (null != users && users.size() > 0) {
            configure = users.get(0);
        } else {
            configure = new Configure();
        }
        return configure;
    }

}
